import '../../../../core/controllers/list_controller.dart';
import '../../../../core/network/api_response.dart';
import '../models/example_item.dart';

class ExampleListController extends ListController<ExampleItem> {
  @override
  Future<ApiResult<PaginationResponse<ExampleItem>>> fetchData({
    required int page,
    required int pageSize,
    String? keyword,
    Map<String, dynamic>? filters,
    String? sortBy,
    String? sortOrder,
  }) async {
    try {
      print('开始加载数据 - page: $page, pageSize: $pageSize');
      // 模拟网络请求延迟
      await Future.delayed(const Duration(milliseconds: 800));
      
      // 生成示例数据
      final allItems = List.generate(50, (index) => ExampleItem(
        id: index + 1,
        title: '示例项目 ${index + 1}',
        description: '这是第 ${index + 1} 个示例项目的描述',
        imageUrl: 'https://picsum.photos/200/200?random=${index + 1}',
        createdAt: DateTime.now().subtract(Duration(days: index)),
        isActive: index % 2 == 0,
      ));
      
      // 搜索过滤
      var filteredItems = allItems;
      if (keyword != null && keyword.isNotEmpty) {
        filteredItems = allItems.where((item) => 
          item.title.toLowerCase().contains(keyword.toLowerCase()) ||
          item.description.toLowerCase().contains(keyword.toLowerCase())
        ).toList();
      }
      
      // 状态过滤
      if (filters != null && filters.containsKey('isActive')) {
        filteredItems = filteredItems.where((item) => 
          item.isActive == filters['isActive']
        ).toList();
      }
      
      // 排序
      if (sortBy != null && sortBy.isNotEmpty) {
        filteredItems.sort((a, b) {
          int comparison = 0;
          switch (sortBy) {
            case 'title':
              comparison = a.title.compareTo(b.title);
              break;
            case 'createdAt':
              comparison = a.createdAt.compareTo(b.createdAt);
              break;
            case 'id':
              comparison = a.id.compareTo(b.id);
              break;
          }
          return sortOrder == 'asc' ? comparison : -comparison;
        });
      }
      
      // 分页
      final startIndex = (page - 1) * pageSize;
      final endIndex = startIndex + pageSize;
      final paginatedItems = filteredItems.sublist(
        startIndex,
        endIndex > filteredItems.length ? filteredItems.length : endIndex,
      );
      
      final totalItems = filteredItems.length;
      final totalPages = (totalItems / pageSize).ceil();
      final hasNext = page < totalPages;
      
      final pagination = PaginationResponse<ExampleItem>(
        items: paginatedItems,
        total: totalItems,
        page: page,
        pageSize: pageSize,
        totalPages: totalPages,
        hasNext: hasNext,
        hasPrevious: page > 1,
      );
      
      print('数据加载成功 - 返回 ${paginatedItems.length} 个项目');
      return ApiResult.success(pagination);
    } catch (e) {
      print('数据加载失败: $e');
      return ApiResult.error('加载数据失败: $e');
    }
  }
  
  @override
  Map<String, dynamic> itemToMap(ExampleItem item) {
    return item.toMap();
  }
  
  @override
  ExampleItem itemFromMap(Map<String, dynamic> map) {
    return ExampleItem.fromMap(map);
  }
  
  // 切换项目状态
  Future<void> toggleItemStatus(int index) async {
    final item = getItem(index);
    if (item != null) {
      final updatedItem = item.copyWith(isActive: !item.isActive);
      updateItem(index, updatedItem);
    }
  }
  
  // 删除项目
  Future<void> deleteItem(int index) async {
    removeItemAt(index);
    showSuccess();
  }
}